<template>
	<view class="container">
		<text class="title">排行榜</text>
		<view class="rank-list">
			<view class="rank-item" v-for="(item, index) in rankList" :key="index">
				<text class="rank-number">{{ index + 1 }}</text>
				<image class="avatar" :src="item.avatar || '/static/avatars/mao.png'" mode="aspectFill"></image>
				<text class="name">{{ item.nickname }}</text>
				<text class="score">{{ item.score }}分</text>
			</view>
		</view>
	</view>
</template>

<script>
	import auth from '../../common/auth.js'
	export default {
		onShow() {
		    // 每次显示页面时检查登录状态
		    if (!auth.checkLogin()) {
		      auth.authInterceptor()
		    }else{
				this.getRankData()
			}
		  },
		data() {
			return {
				rankList: [
					{
						name: '钱七',
						score: 86,
						avatar: '/static/avatars/5.jpg'
					}
				]
			}
		},
		
		methods: {
			async getRankData() {
				try {
					const token = uni.getStorageSync('token')
					const res = await uni.request({
						url: 'http://localhost:8003/api/v1/user/rank',
						method: 'GET',
						header: {
							'Authorization': 'Bearer ' + token
						}
					})
		
					if (res.statusCode === 200 && res.data.code === 200) {
						let result = res.data.data;
						this.rankList = res.data.data
					} else {
						throw new Error(res.data.message || '加载游戏数据失败')
					}
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					})
				}
			},
		}
	}
</script>

<style>
	.container {
		padding: 20px;
	}

	.title {
		font-size: 24px;
		font-weight: bold;
		margin-bottom: 20px;
		display: block;
	}

	.rank-list {
		width: 100%;
	}

	.rank-item {
		display: flex;
		align-items: center;
		padding: 15px 0;
		border-bottom: 1px solid #f0f0f0;
	}

	.rank-number {
		width: 30px;
		text-align: center;
		font-size: 18px;
		font-weight: bold;
		color: #ff9900;
	}

	.avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin: 0 15px;
	}

	.name {
		flex: 1;
		font-size: 16px;
	}

	.score {
		color: #ff9900;
		font-weight: bold;
	}
</style>